package com.xuyuan.agent.cglib;

import com.xuyuan.agent.intro.OrderService;
import com.xuyuan.agent.intro.OrderServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private static CglibProxy INSTANCE = new CglibProxy();

    private Object target;

    private Class<?> clazz;


    private CglibProxy() {
    }

    public CglibProxy(Class<?> clazz) {
        this.clazz = clazz;
    }

    public static CglibProxy getInstance() {
        return INSTANCE;
    }

    public Object getCglibProxyObject(Object target) {
        // 可以在Spring中获取指定对象，为其创建代理对象，再指定对应的target
        this.clazz = target.getClass();
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    /**
     * @param object 被代理的对象
     * @param method 被代理对象需要执行的方法
     * @param args   被代理对象需要执行的方法 参数
     * @param proxy  触发父类的方法对象
     * @return 被代理对象需要执行的方法 返回值
     * @throws Throwable 抛出的异常信息
     */
    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Before method execution: " + method.getName());
        Object result = proxy.invokeSuper(object, args);
        System.out.println("After method execution: " + method.getName());
        return result;
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OrderServiceImpl.class);
        enhancer.setCallback(new CglibProxy());
        OrderService orderService = (OrderService) enhancer.create();
        orderService.save();
    }
}